/*
(non-Javadoc)

@see com.impetus.kundera.index.Indexer#search(java.lang.String,
java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata,
java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata,
java.lang.Object, int, int)
517116
@Override
    public Map<String, Object> search(String query, Class<?> parentClass, EntityMetadata parentMetadata,
            Class<?> childClass, EntityMetadata childMetadata, Object entityId, int start, int count)
    {
        return search(parentClass, parentMetadata, query, start, count);
    }
1312462
@Override
    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        // find by relational value !

        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,
                entityMetadata.getPersistenceUnit());

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

        Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());

        Iterator<Row> rowsIter = null;
        if (schemaTable.getPrimaryKey().contains(colName))
        {
            PrimaryKey rowKey = schemaTable.createPrimaryKey();
            NoSqlDBUtils.add(schemaTable.getField(colName), rowKey, colValue, colName);
            rowsIter = tableAPI.tableIterator(rowKey, null, null);
        }
        else
        {
            Index index = schemaTable.getIndex(colName);
            IndexKey indexKey = index.createIndexKey();
            NoSqlDBUtils.add(schemaTable.getField(colName), indexKey, colValue, colName);
            rowsIter = tableAPI.tableIterator(indexKey, null, null);
        }

        try
        {
            Map<String, Object> relationMap = initialize(entityMetadata);

            return scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap, null);
        }
        catch (Exception e)
        {
            log.error("Error while finding data for Key " + colName + ", Caused By :" + e + ".");
            throw new PersistenceException(e);
        }

    }
243747
@Override
    public Object find(Class entityClass, Object key)
    {
        HttpResponse response = null;
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());
        try
        {
            if (key instanceof JsonElement)
            {
                key = ((JsonElement) key).getAsString();
            }
            String _id = null;
            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
            {
                Field field = (Field) entityMetadata.getIdAttribute().getJavaMember();
                EmbeddableType embeddableType = metaModel.embeddable(entityMetadata.getIdAttribute()
                        .getBindableJavaType());
                _id = CouchDBObjectMapper.get_Id(field, key, embeddableType, entityMetadata.getTableName());
            }
            else
            {
                _id = entityMetadata.getTableName() + PropertyAccessorHelper.getString(key);
            }

            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                    CouchDBConstants.URL_SEPARATOR + entityMetadata.getSchema().toLowerCase()
                            + CouchDBConstants.URL_SEPARATOR + _id, null, null);
            HttpGet get = new HttpGet(uri);
            get.addHeader("Accept", "application/json");
            response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));

            InputStream content = response.getEntity().getContent();
            Reader reader = new InputStreamReader(content);

            JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);

            // Check for deleted object. if object is deleted then return null.
            if (jsonObject.get(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()) == null)
            {
                return null;
            }

            return CouchDBObjectMapper.getEntityFromJson(entityClass, entityMetadata, jsonObject,
                    entityMetadata.getRelationNames(), kunderaMetadata);
        }
        catch (Exception e)
        {
            log.error("Error while finding object by key {}, Caused by {}.", key, e);
            throw new KunderaException(e);
        }
        finally
        {
            closeContent(response);
        }
    }
1305132
@Override
    public EntityIdentifier[] searchForGroups(
            final String query,
            final SearchMethod method,
            @SuppressWarnings("unchecked") final Class leaftype) {

        // only search for groups
        if (leaftype != IPerson.class) {
            return new EntityIdentifier[] {};
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Searching Grouper for groups matching query: " + query);
        }

        // result groups.
        List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>();

        try {

            // TODO: searches need to be performed against the group display
            // name rather than the group key

            GcFindGroups groupSearch = new GcFindGroups();
            WsQueryFilter filter = new WsQueryFilter();
            // is this an exact search or fuzzy
            if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) {
                filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT");
            } else {
                filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE");
            }
            filter.setGroupName(query);
            groupSearch.assignQueryFilter(filter);
            WsFindGroupsResults results = groupSearch.execute();

            if (results != null && results.getGroupResults() != null) {
                for (WsGroup g : results.getGroupResults()) {
                    if (validKey(g.getName())) {
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("Retrieved group: " + g.getName());
                        }
                        groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class));
                    }
                }
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Returning " + groups.size() + " results for query " + query);
            }

            return groups.toArray(new EntityIdentifier[groups.size()]);

        } catch (Exception e) {
            LOGGER.warn(
                    "Exception while attempting to retrieve "
                            + "search results for query "
                            + query
                            + " and entity type "
                            + leaftype.getCanonicalName()
                            + " : "
                            + e.getMessage());
            return new EntityIdentifier[] {};
        }
    }
409215
@Override
    public void _search(String fieldName, String searchTerms, SearchOperator operator) {
        List<QueryToken> tokens = getCurrentWhereTokens();
        appendOperatorIfNeeded(tokens);

        fieldName = ensureValidFieldName(fieldName, false);
        negateIfNeeded(tokens, fieldName);

        WhereToken whereToken = WhereToken.create(WhereOperator.SEARCH, fieldName, addQueryParameter(searchTerms), new WhereToken.WhereOptions(operator));
        tokens.add(whereToken);
    }
686536
@Override
    public Object find(Class entityClass, Object key)
    {
        GraphDatabaseService graphDb = null;
        if (resource != null)
        {
            graphDb = getConnection();
        }

        if (graphDb == null)
            graphDb = factory.getConnection();

        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);

        Object entity = null;
        Node node = mapper.searchNode(key, m, graphDb, true);

        if (node != null && !((Neo4JTransaction) resource).containsNodeId(node.getId()))

        {
            entity = getEntityWithAssociationFromNode(m, node);
        }

        return entity;
    }
105718
public SearchResponse searchAll(boolean isSetExplain, String[] indices,
            String[] types, QueryBuilder filterQueryBuilder) {
        return searchAll(isSetExplain, indices, types,
                filterQueryBuilder, null);
    }
1313675
@Override
    public Object find(Class entityClass, Object rowId)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        Object enhancedEntity = null;
        if (rowId == null)
        {
            return null;
        }
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());
        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))
        {
            rowId = KunderaCoreUtils.prepareCompositeKey(m, rowId);
        }
        try
        {
            List results = findData(m, rowId, null, null, null, null);
            if (results != null && !results.isEmpty())
            {
                enhancedEntity = results.get(0);
            }
        }
        catch (Exception e)
        {
            log.error("Error during find by id, Caused by: .", e);
            throw new KunderaException("Error during find by id, Caused by: .", e);
        }
        return enhancedEntity;
    }
650631
public SearchResponse searchAll(String index, String type,
            QueryBuilder filterQueryBuilder) {
        return searchAll(index, type, filterQueryBuilder, null);
    }
215336
@Override
    public Object find(Class entityClass, Object key)
    {

        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(entityMetadata.getPersistenceUnit());
        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());

        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getName();

        Field field = (Field) entityType.getAttribute(idColumnName).getJavaMember();

        Type idType = KuduDBValidationClassMapper.getValidTypeForClass(field.getType());

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

        KuduScannerBuilder scannerBuilder = kuduClient.newScannerBuilder(table);
        KuduScanner scanner = null;

        if (entityType.getAttribute(idColumnName).getJavaType().isAnnotationPresent(Embeddable.class))
        {
            // Composite Id
            EmbeddableType embeddableIdType = metaModel.embeddable(entityType.getAttribute(idColumnName).getJavaType());
            Field[] fields = entityType.getAttribute(idColumnName).getJavaType().getDeclaredFields();

            addPredicatesToScannerBuilder(scannerBuilder, embeddableIdType, fields, metaModel, key);
        }
        else
        {
            // Simple Id
            ColumnSchema column = new ColumnSchema.ColumnSchemaBuilder(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(), idType).build();

            KuduPredicate predicate = KuduDBDataHandler.getEqualComparisonPredicate(column, idType, key);
            scannerBuilder.addPredicate(predicate);
        }

        scanner = scannerBuilder.build();

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

            while (results.hasNext())
            {
                RowResult result = results.next();
                entity = KunderaCoreUtils.createNewInstance(entityClass);
                populateEntity(entity, result, entityType, metaModel);
                logger.debug(result.rowToString());
            }
        }
        return entity;
    }
465482
@Override
    public List<SearchResult> search(EntityMetadata m, String persistenceUnit, ConsistencyLevel consistencyLevel,
            Map<Boolean, List<IndexClause>> indexClauseMap)
    {

        return super.search(m, persistenceUnit, consistencyLevel, indexClauseMap);
    }
534740
@Override
    public Object find(Class entityClass, Object key)
    {
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());

        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());

        return managedType.hasLobAttribute() ? findGFSEntity(entityMetadata, entityClass, key) : find(entityClass, key,
                entityMetadata, metaModel, managedType);
    }
915080
public <T> ESDatas<T> searchAllParallel(String index,  Class<T> type,int thread) throws ElasticSearchException{
			return searchAllParallel(index,  ClientInterface.DEFAULT_FETCHSIZE,type,thread);
	}
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;
    }
97741
public  <T> ESDatas<T> searchAll(String index,  int fetchSize ,Class<T> type) throws ElasticSearchException{
		return searchAll(index,  fetchSize ,(ScrollHandler<T>) null,type);
	}
1062832
public final void write(EntityMetadata metadata, Object entity)
    {
        if (indexer != null)
        {
            MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    metadata.getPersistenceUnit());
            ((com.impetus.kundera.index.lucene.Indexer) indexer).index(metadata, metamodel, entity);
        }
    }
453152
@Override
    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

        String columnFamilyName = m.getTableName();

        byte[] valueInBytes = HBaseUtils.getBytes(colValue);
        SingleColumnValueFilter f = new SingleColumnValueFilter(Bytes.toBytes(columnFamilyName),
                Bytes.toBytes(colName), CompareOp.EQUAL, valueInBytes);

        List output = new ArrayList();
        try
        {
            List<AbstractManagedType> subManagedType = getSubManagedType(entityClazz, m);

            if (!subManagedType.isEmpty())
            {
                for (AbstractManagedType subEntity : subManagedType)
                {
                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            subEntity.getJavaType());
                    List results = ((HBaseDataHandler) handler).scanData(f, subEntityMetadata.getSchema(),
                            subEntityMetadata.getEntityClazz(), subEntityMetadata, columnFamilyName, colName);
                    if (!results.isEmpty())
                    {
                        output.addAll(results);
                    }
                }
            }
            else
            {
                return ((HBaseDataHandler) handler).scanData(f, m.getSchema(), entityClazz, m, columnFamilyName,
                        colName);
            }
        }
        catch (IOException ioe)
        {
            log.error("Error during find By Relation, Caused by: .", ioe);
            throw new KunderaException(ioe);
        }
        catch (InstantiationException ie)
        {
            log.error("Error during find By Relation, Caused by: .", ie);
            throw new KunderaException(ie);
        }
        catch (IllegalAccessException iae)
        {
            log.error("Error during find By Relation, Caused by: .", iae);
            throw new KunderaException(iae);
        }

        return output;
    }