/*
(non-Javadoc)

@see
com.impetus.kundera.persistence.AbstractEntityReader#findById(java.lang
.Object, com.impetus.kundera.metadata.model.EntityMetadata,
com.impetus.kundera.client.Client)
968386
@Override
    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)
    {
        return super.findById(primaryKey, m, client);
    }
973907
public Finder<SQLProperty> getEntityBySimpleName(String entityName) {
		if (entityName == null)
			return null;

		SQLiteEntity result = entitiesBySimpleName.get(entityName.toLowerCase());
		if (result != null)
			return result;

		for (GeneratedTypeElement item : this.generatedEntities) {
			if (item.typeSpec.name.toLowerCase().equals(entityName.toLowerCase())) {
				return item;
			}
		}

		return null;
	}
260325
@Override
    public boolean existsById(ID primaryKey) {
        Assert.notNull(primaryKey, "primaryKey should not be null");

        return findById(primaryKey).isPresent();
    }
771564
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
            Object columnValue, Class entityClazz)
    {
        return getColumnsById(schemaName, tableName, columnName, pKeyName, columnValue, entityClazz).toArray();
    }
824282
public Transaction findByTransactionId(String transactionId) {
        EntityManager entityManager = getEntityManager();
        try {
            return entityManager.createQuery("SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Transaction AS t WHERE t.transactionId = :transactionId", Transaction.class)
                    .setParameter("transactionId", transactionId)
                    .getSingleResult();
        } finally {
            entityManager.close();
        }
    }
663387
@Override
    public <T> T find(Class<T> entityClass, Object primaryKey)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "em.find(" + entityClass + ',' + primaryKey + ");\n" + toString());

        return getEMInvocationInfo(false).find(entityClass, primaryKey);
    }
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;
    }
548045
@Override
    public <T> T find(Class<T> entityClass, Object primaryKey)
    {
        try
        {
            return ivEm.find(entityClass, primaryKey);
        } finally
        {
            if (!inJTATransaction())
            {
                ivEm.clear();
            }
        }
    }
900342
@Override
    public Object find(Class entityClass, Object key)
    {
        Object result = null;
        Object connection = getConnection();
        try
        {
            result = fetch(entityClass, key, connection, null);
        }
        catch (InstantiationException e)
        {
            logger.error("Error during find by key:", e);
            throw new PersistenceException(e);
        }
        catch (IllegalAccessException e)
        {
            logger.error("Error during find by key:", e);
            throw new PersistenceException(e);
        }
        finally
        {
            onCleanup(connection);
        }

        return result;
    }
956430
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
            Object columnValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

        byte[] valueInBytes = HBaseUtils.getBytes(columnValue);
        Filter f = new SingleColumnValueFilter(Bytes.toBytes(tableName), Bytes.toBytes(columnName), CompareOp.EQUAL,
                valueInBytes);
        KeyOnlyFilter keyFilter = new KeyOnlyFilter();
        FilterList filterList = new FilterList(f, keyFilter);
        try
        {
            return handler.scanRowyKeys(filterList, schemaName, tableName, columnName + "_" + columnValue, m
                    .getIdAttribute().getBindableJavaType());
        }
        catch (IOException e)
        {
            log.error("Error while executing findIdsByColumn(), Caused by: .", e);
            throw new KunderaException(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);
        }
    }
1328635
function findById(id, cb) {
  db.getClient(function(err, client, done) {
    client.query(SELECT_ID, [id], function(err, r) {
      var result = r && r.rows[0];
      if(!err && !result) err = new exceptions.NotFound();
      if(err) {
        cb(err);
        done(err);
      } else {
        cb(null, result);
        done();
      }
    });
  });
}
1325269
public <E> E findById(final Class<E> entityClass, final Object primaryKey)
    {
        E e = find(entityClass, primaryKey);
        if (e == null)
        {
            return null;
        }

        // Return a copy of this entity
        return (E) (e);
    }
1291687
@Override
  public Entity findOneById(Object id) {
    if (cacheable
        && !transactionInformation.isEntireRepositoryDirty(getEntityType())
        && !transactionInformation.isEntityDirty(EntityKey.create(getEntityType(), id))) {
      return l2Cache.get(delegate(), id);
    }
    return delegate().findOneById(id);
  }
690668
public E findById(ID id) {
        LOG.trace("Finding " + entityClass.getSimpleName() + " with ID " + id);
        return (E) getSession().get(entityClass, id);
    }
686983
@Override
    public T getById(Object id)
    {
        return context.getFramed().getFramedVertex(this.type, id);
    }
647522
@Override
    public Object find(Class entityClass, Object rowId) {
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        StringBuilder builder = createSelectQuery(rowId, metadata, metadata.getTableName());
        ResultSet rSet = this.execute(builder.toString(), null);
        List results = iterateAndReturn(rSet, metadata);
        return results.isEmpty() ? null : results.get(0);
    }