/*
(non-Javadoc)

@see com.impetus.kundera.client.Client#find(java.lang.Class,
java.lang.Object)
350258
@Override
    public Object find(Class entityClass, Object key)
    {

        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        JsonDocument doc;
        String id = generateJsonDocId(entityMetadata.getTableName(), key.toString());
        doc = bucket.get(id);
        LOGGER.debug("Found result for ID : " + key.toString() + " in the " + bucket.name() + " Bucket");

        if (doc == null)
        {
            return null;
        }
        else
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                    .getMetamodel(entityMetadata.getPersistenceUnit());
            EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
            return handler.getEntityFromDocument(entityClass, doc.content(), entityType);
        }
    }
926716
@Override
  public void find(byte []tableKey, 
                   Object arg, 
                   Result<byte[]> result)
  {
    TableKraken table = _tableManager.getTable(tableKey);
    
    if (table == null) {
      throw new QueryException(L.l("'{0}' is an unknown table.",
                                   Hex.toShortHex(tableKey)));
    }
      
    String sql = "select_local table_key from kraken_meta_table where table_name=?";
      
    QueryBuilderKraken builder = QueryParserKraken.parse(_tableManager, sql);
      
    QueryKraken query = builder.build();
    
    query.findOne(result.then(cursor->findKeyResult(cursor)), arg);
  }
534322
@Override
  public <T> T findById(Object id, Class<T> entityClass) {
    return findById(id, Util.determineCollectionName(entityClass));
  }
373136
@Override
	public Collection<T> find(final SearchTerm[] terms, JiteratorFilter<T> filter,
			Boolean orderDesc, String... orderFields)
			throws PersistenceException {

		PopulatorThread<T> populator;

		populator = new PopulatorThread<T>(new JiteratorPopulator<T>() {
			public void populate(Jiterator<T> iterator) throws PersistenceException {
				ResultSet rs = null;
				try {             
					String index = null;
					String[] values = new String[terms.length];
					FindOperator operator = null;

					for (int i = 0; i < terms.length; i++) {
						// since no other way to get index, just assume column
						index = terms[i].getColumn(); 
						values[i] = terms[i].getValue().toString();		
						
						switch (terms[i].getOperator()) {
							case EQUALS: operator = FindOperator.EQ; break;
							case GREATER_THAN: operator = FindOperator.GT; break;
							case GREATER_THAN_OR_EQUAL_TO: operator = FindOperator.GE; break;
							case LESS_THAN: operator = FindOperator.LT; break;
							case LESS_THAN_OR_EQUAL_TO: operator = FindOperator.LE; break;
							default: throw new PersistenceException("Operator " + operator + " not supported!");							
						}						
					}

					// open a session to retrieve the primary key of the table by the values of the specified index
					rs = getSession(index, getPrimaryKeyField()).find(values, operator, 1, 0);

					// for each row, get the object from cache
					while (rs.next()) {
						T object = get(getValue(getPrimaryKeyField(), 1, rs));
						if (object != null) {
							iterator.push(object);
						}
					}
				} catch (Exception e) {
					throw new PersistenceException(e.getMessage());
				} finally {
					try {
						rs.close();
					} catch (SQLException e) {
						throw new PersistenceException(e.getMessage());
					}
				}
			}
		});
		populator.populate();
		return populator.getResult();
	}
1255750
@Override
  public <T> T find(Class<T> beanType, Object id) {
    methodCalls.add(MethodCall.of("find").with("beanType", beanType, "id", id));
    WhenBeanReturn match = whenFind.findMatchById(beanType, id);
    if (match != null) {
      return (T)match.val();
    }
    return find.find(beanType, id, null);
  }
106315
@Override
    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        List<Object> entities = null;

        if (isCql3Enabled(m))
        {
            entities = new ArrayList<Object>();

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

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

            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

            if (subManagedType.isEmpty())
            {
                entities.addAll(findByRelationQuery(m, colName, colValue, entityClazz, dataHandler));
            }
            else
            {
                for (AbstractManagedType subEntity : subManagedType)
                {
                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            subEntity.getJavaType());

                    entities.addAll(findByRelationQuery(subEntityMetadata, colName, colValue,
                            subEntityMetadata.getEntityClazz(), dataHandler));
                    // TODOO:: if(entities != null)
                }
            }

        }
        else
        {
            SlicePredicate slicePredicate = new SlicePredicate();
            slicePredicate.setSlice_range(new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER,
                    ByteBufferUtil.EMPTY_BYTE_BUFFER, false, Integer.MAX_VALUE));

            IndexExpression ie = new IndexExpression(UTF8Type.instance.decompose(colName), IndexOperator.EQ,
                    ByteBuffer.wrap(PropertyAccessorHelper.getBytes(colValue)));
            List<IndexExpression> expressions = new ArrayList<IndexExpression>();
            expressions.add(ie);

            IndexClause ix = new IndexClause();
            ix.setStart_key(ByteBufferUtil.EMPTY_BYTE_BUFFER);
            ix.setCount(Integer.MAX_VALUE);
            ix.setExpressions(expressions);
            ColumnParent columnParent = new ColumnParent(m.getTableName());

            List<KeySlice> keySlices = null;
            Connection conn = null;

            try
            {
                conn = getConnection();
                if (!m.getType().equals(Type.SUPER_COLUMN_FAMILY))
                {
                    keySlices = conn.getClient().get_indexed_slices(columnParent, ix, slicePredicate,
                            getConsistencyLevel());
                }
            }
            catch (InvalidRequestException e)
            {
                if (e.why != null && e.why.contains("No indexed columns"))
                {
                    return entities;
                }
                else
                {
                    log.error("Error while finding relations for column family {} , Caused by: .", m.getTableName(), e);
                    throw new KunderaException(e);
                }
            }
            catch (UnavailableException e)
            {
                log.error("Error while finding relations for column family {} , Caused by: .", m.getTableName(), e);
                throw new KunderaException(e);
            }
            catch (TimedOutException e)
            {
                log.error("Error while finding relations for column family {} , Caused by: .", m.getTableName(), e);
                throw new KunderaException(e);
            }
            catch (TException e)
            {
                log.error("Error while finding relations for column family {} , Caused by: .", m.getTableName(), e);
                throw new KunderaException(e);
            }
            finally
            {
                releaseConnection(conn);
            }

            if (keySlices != null)
            {
                entities = new ArrayList<Object>(keySlices.size());

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

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

                List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

                if (subManagedType.isEmpty())
                {
                    entities = populateData(m, keySlices, entities, m.getRelationNames() != null, m.getRelationNames());
                }
                else
                {
                    for (AbstractManagedType subEntity : subManagedType)
                    {
                        EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                subEntity.getJavaType());
                        entities = populateData(subEntityMetadata, keySlices, entities,
                                subEntityMetadata.getRelationNames() != null, subEntityMetadata.getRelationNames());
                        // TODOO:: if(entities != null)

                    }
                }
            }
        }
        return entities;
    }
1305819
private Object find(Class entityClass, Object key, List<String> columnsToSelect)
    {
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,
                entityMetadata.getPersistenceUnit());

        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();
        Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());

        PrimaryKey rowKey = schemaTable.createPrimaryKey();
        if (metamodel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
        {
            readEmbeddable(key, columnsToSelect, entityMetadata, metamodel, schemaTable, rowKey,
                    entityMetadata.getIdAttribute());
        }
        else
        {
            if (eligibleToFetch(columnsToSelect, idColumnName))
            {
                NoSqlDBUtils.add(schemaTable.getField(idColumnName), rowKey, key, idColumnName);
            }
        }
        KunderaCoreUtils.printQuery("Fetch data from " + entityMetadata.getTableName() + " for PK " + key, showQuery);
        if (log.isDebugEnabled())
        {
            log.debug("Fetching data from " + entityMetadata.getTableName() + " for PK " + key);
        }

        // Object entity = null;
        List entities = new ArrayList();
        Map<String, Object> relationMap = initialize(entityMetadata);

        try
        {
            Iterator<Row> rowsIter = tableAPI.tableIterator(rowKey, null, null);
            // iterator and build entity
            entities = scrollAndPopulate(key, entityMetadata, metamodel, schemaTable, rowsIter, relationMap,
                    columnsToSelect);
        }
        catch (Exception e)
        {
            log.error("Error while finding data for Key " + key + ", Caused By :" + e + ".");
            throw new PersistenceException(e);
        }

        return entities.isEmpty() ? null : entities.get(0);
    }
407458
@Override
    public Object find(Class clazz, Object key)
    {
        s = getStatelessSession();

        Object result = null;
        try
        {
            result = s.get(clazz, (Serializable) key);
        }
        catch (ClassCastException ccex)
        {
            log.error("Class can not be serializable, Caused by {}.", ccex);
            throw new KunderaException(ccex);
        }
        catch (Exception e)
        {
            log.error("Error while finding, Caused by {}. ", e);
            throw new KunderaException(e);
        }
        return result;

    }
899775
public <T, K extends Serializable>
    T findById(
                    final Class<T> type,
                    final K id
                    )
    {
       _LOG_.info( "findById: type=" + type + ", ID=" + id );
       long  ts_start = System.currentTimeMillis();

       T  p_object = null;
       try {
           p_object = getDAO( type ).get( id );
       } catch (Exception ex) {
           throw new RepositoryException( ex );
       }

       _LOG_.info( "findById: elapsed time (ms)=" +  (System.currentTimeMillis() - ts_start) );
       _LOG_.debug( (p_object == null ? "findById: object NOT found" : "findById: object found") );
       if (p_object == null) {
           ObjectNotFoundException  ex = new ObjectNotFoundException( "type=" + type + ", id=" + id );
           ex.setType( type );
           ex.setId( id );
           throw ex;
       }

       return p_object;
   }
868550
public static Field findField(String className, String fieldName) throws ClassNotFoundException {
        JavaClass jclass = Repository.lookupClass(className);

        while (jclass != null) {
            Field[] fieldList = jclass.getFields();
            for (Field field : fieldList) {
                if (field.getName().equals(fieldName)) {
                    return field;
                }
            }

            jclass = jclass.getSuperClass();
        }

        return null;
    }
405108
public <ResultT> ResultT findOne(final Class<ResultT> resultClass) {
    return executeFindOne(new BsonDocument(), null, resultClass);
  }
1124852
@Override
    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)
    {
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);

        log.debug("Fetching data from " + entityMetadata.getTableName() + " for Keys " + keys);

        DBCollection dbCollection = mongoDb.getCollection(entityMetadata.getTableName());

        BasicDBObject query = new BasicDBObject();

        query.put("_id", new BasicDBObject("$in", keys));

        DBCursor cursor = dbCollection.find(query);
        KunderaCoreUtils.printQuery("Find collection:" + query, showQuery);
        List entities = new ArrayList<E>();
        while (cursor.hasNext())
        {
            DBObject fetchedDocument = cursor.next();

            populateEntity(entityMetadata, entities, fetchedDocument);
        }
        return entities;
    }
1158527
protected static Class findClass(final String className) throws ClassNotFoundException {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            try {
                return Class.forName(className);
            } catch (ClassNotFoundException e1) {
                return MavenCoordHelper.class.getClassLoader().loadClass(className);
            }
        }
    }
864635
public function find($class, $id)
    {
        if (!isset($id)) {
            return;
        }

        if (null === $class) {
            return $this->dm->find(null, $id);
        }

        return $this->dm->getRepository($class)->find($id);
    }
458894
@Override
   @SuppressWarnings("rawtypes")
   protected Class<?> findClass(String name) throws ClassNotFoundException {
      if (classCache.containsKey(name)) {
         return classCache.get(name);
      }

      for (WeakReference<Bundle> ref : bundles) {
         final Bundle bundle = ref.get();
         // ISPN-4679 may get a null handle from the weak reference
         if (bundle == null) continue;
         if (bundle.getState() == Bundle.ACTIVE) {
            try {
               final Class clazz = bundle.loadClass(name);
               if (clazz != null) {
                  classCache.put(name, clazz);
                  return clazz;
               }
            } catch (Exception ignore) {
            }
         }
      }

      throw new ClassNotFoundException("Could not load requested class : " + name);
   }
620603
@Override
    public Object find(Class entityClass, Object rowId)
    {
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        List<String> relationNames = entityMetadata.getRelationNames();
        // columnFamily has a different meaning for HBase, so it won't be used
        // here
        String tableName = entityMetadata.getSchema();
        Object enhancedEntity = null;
        List results = null;
        try
        {
            if (rowId == null)
            {
                return null;
            }

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

            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
            {
                rowId = KunderaCoreUtils.prepareCompositeKey(entityMetadata, rowId);
            }

            results = fetchEntity(entityClass, rowId, entityMetadata, relationNames, tableName, results, null, null);

            if (results != null && !results.isEmpty())
            {
                enhancedEntity = results.get(0);
            }
        }
        catch (IOException e)
        {
            log.error("Error during find by id, Caused by: .", e);
            throw new KunderaException(e);
        }
        return enhancedEntity;
    }
1336998
@Override
  public <T> T findOne(String jxQuery, Class<T> entityClass) {
    return findOne(jxQuery, Util.determineCollectionName(entityClass));
  }