/*
Finds the findByPrimaryKey method in the bean's home interface
548236
private Method findFindByPrimaryKey(Class c)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "findFindByPrimaryKey", c);

        Method[] methods = c.getMethods();

        for (int i = 0; i < methods.length; ++i)
        {
            if (methods[i].getName().equals("findByPrimaryKey"))
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    Tr.exit(tc, "findFindByPrimaryKey");
                return methods[i];
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "findFindByPrimaryKey: method findByPrimaryKey not found!");
        return null;
    }
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);
  }
615660
@Override
    public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException
    {
        assert(table != null && !table.isEmpty());
        checkClosed();
        this.sysCatalog.setString(1, "PRIMARYKEYS");
        JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery();
        VoltTable vtable = res.getVoltTable().clone(0);

        // Filter the primary keys based on table name
        while (res.next()) {
            if (res.getString("TABLE_NAME").equals(table)) {
                vtable.addRow(res.getRowData());
            }
        }
        return new JDBC4ResultSet(sysCatalog, vtable);
    }
318381
public static <T> T find(Class<T> factoryClass, Map<String, String> propertyMap) {
		return findInternal(factoryClass, propertyMap, Optional.empty());
	}
479635
@Override
  int findKey(final byte[] key) {
    final long[] hash = MurmurHash3.hash(key, SEED);
    int entryIndex = getIndex(hash[0], tableEntries_);
    int firstDeletedIndex = -1;
    final int loopIndex = entryIndex;
    do {
      if (isBitClear(stateArr_, entryIndex)) {
        return firstDeletedIndex == -1 ? ~entryIndex : ~firstDeletedIndex; // found empty or deleted
      }
      if (couponsArr_[entryIndex * maxCouponsPerKey_] == 0) { //found deleted
        if (firstDeletedIndex == -1) { firstDeletedIndex = entryIndex; }
      } else if (Map.arraysEqual(keysArr_, entryIndex * keySizeBytes_, key, 0, keySizeBytes_)) {
        return entryIndex; // found key
      }
      entryIndex = (entryIndex + getStride(hash[1], tableEntries_)) % tableEntries_;
    } while (entryIndex != loopIndex);
    throw new SketchesArgumentException("Key not found and no empty slots!");
  }
3407
@SuppressWarnings("rawtypes")
public static Object getMappedProperty(Object bean, String name, String key)
       throws IllegalAccessException, InvocationTargetException, NoSuchMethodException,Exception
   {
       if(bean == null)
           throw new IllegalArgumentException("No bean specified");
       if(name == null)
           throw new IllegalArgumentException("No name specified");
       if(key == null)
           throw new IllegalArgumentException("No key specified");
       
       Object result = null;
       PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
       if(descriptor == null)
           throw new NoSuchMethodException("Unknown property '" + name + "'");
       if(descriptor instanceof JBPropertyDescriber)
       {
           Method readMethod = ((JBPropertyDescriber)descriptor).getMappedReadMethod();
           if(readMethod != null)
           {
               Object keyArray[] = new Object[1];
               keyArray[0] = key;
               result = readMethod.invoke(bean, keyArray);
           } else
           {
               throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method");
           }
       } else
       {
           Method readMethod = descriptor.getReadMethod();
           if(readMethod != null)
           {
               Object invokeResult = readMethod.invoke(bean, new Object[0]);
               if(invokeResult instanceof Map)
                   result = ((Map)invokeResult).get(key);
           } else
           {
               throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method");
           }
       }
       return result;
   }
1196640
@Override
	public CPRule fetchByPrimaryKey(Serializable primaryKey) {
		Serializable serializable = entityCache.getResult(CPRuleModelImpl.ENTITY_CACHE_ENABLED,
				CPRuleImpl.class, primaryKey);

		if (serializable == nullModel) {
			return null;
		}

		CPRule cpRule = (CPRule)serializable;

		if (cpRule == null) {
			Session session = null;

			try {
				session = openSession();

				cpRule = (CPRule)session.get(CPRuleImpl.class, primaryKey);

				if (cpRule != null) {
					cacheResult(cpRule);
				}
				else {
					entityCache.putResult(CPRuleModelImpl.ENTITY_CACHE_ENABLED,
						CPRuleImpl.class, primaryKey, nullModel);
				}
			}
			catch (Exception e) {
				entityCache.removeResult(CPRuleModelImpl.ENTITY_CACHE_ENABLED,
					CPRuleImpl.class, primaryKey);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return cpRule;
	}
1211004
private List<Object> findUsingLucene(EntityMetadata m, Client client, Object[] primaryKeys)
    {

        String idField = m.getIdAttribute().getName();
        String equals = "=";
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());
        EntityType entityType = metaModel.entity(m.getEntityClazz());
        String columnName = ((AbstractAttribute) entityType.getAttribute(idField)).getJPAColumnName();
        List<Object> result = new ArrayList<Object>();
        Queue queue = getKunderaQuery().getFilterClauseQueue();
        KunderaQuery kunderaQuery = getKunderaQuery();

        for (Object primaryKey : primaryKeys)
        {
            FilterClause filterClause = kunderaQuery.new FilterClause(columnName, equals, primaryKey, idField);
            kunderaQuery.setFilter(kunderaQuery.getEntityAlias() + "." + columnName + " = " + primaryKey);
            queue.clear();
            queue.add(filterClause);
            List<Object> object = findUsingLucene(m, client);
            if (object != null && !object.isEmpty())
                result.add(object.get(0));
        }
        return result;
    }
1200047
public KeyExporter findKeyExporterByPublicKey(PublicKey publicKey) {
      PrivateKey key = _privateKeys.get(publicKey);
      if (key instanceof KeyExporter) {
         return (KeyExporter) key;
      }
      return null;
   }
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);
        }
    }
418286
public Object getPrimaryKey() throws javax.ejb.EJBException
    {
        HomeInternal hi = beanId.getHome();

        if (hi.isStatelessSessionHome() || hi.isStatefulSessionHome()) {
            throw new IllegalSessionMethodLocalException();
        }

        //PK26539: copy the primary key (see WASInternal_copyPrimaryKey for explanation)
        return ((EJSHome) hi).WASInternal_copyPrimaryKey(beanId.getPrimaryKey());
    }
1025665
private static Method findSetMethod(Class<? extends Bean> beanType, String setterName, Class<?> fieldType) {
        try {
            return beanType.getDeclaredMethod(setterName, fieldType);
        } catch (NoSuchMethodException ex) {
            Method[] methods = beanType.getMethods();
            List<Method> potential = new ArrayList<>();
            for (Method method : methods) {
                if (method.getName().equals(setterName) && method.getParameterTypes().length == 1) {
                    potential.add(method);
                }
            }
            if (potential.size() == 1) {
                return potential.get(0);
            }
            for (Method method : potential) {
                if (method.getParameterTypes()[0].equals(fieldType)) {
                    return method;
                }
            }
            return null;
        }
    }
266233
@SuppressWarnings("unchecked")
  @Override
  public <T> T findById(Object id, String collectionName) {
    CollectionMetaData cmd = cmdMap.get(collectionName);
    Map<Object, T> collection = (Map<Object, T>) collectionsRef.get().get(collectionName);
    if((null == cmd) || null == collection) {
      throw new InvalidJsonDbApiUsageException("Collection by name '" + collectionName + "' not found. Create collection first.");
    }
    cmd.getCollectionLock().readLock().lock();
    try {
      Object obj = Util.deepCopy(collection.get(id));
      if(encrypted && cmd.hasSecret() && null != obj){
        CryptoUtil.decryptFields(obj, cmd, dbConfig.getCipher());
      }
      return (T) obj;
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
      logger.error("Error when decrypting value for a @Secret annotated field for entity: " + collectionName, e);
      throw new JsonDBException("Error when decrypting value for a @Secret annotated field for entity: " + collectionName, e);
    } finally {
      cmd.getCollectionLock().readLock().unlock();
    }
  }
347520
private Method findAddRemoveListenerMethod(Class<?> sourceClass, String methodName) throws IntrospectionException
	{
		try
		{
			return sourceClass.getMethod(methodName, listenerType);
		}
		catch (NoSuchMethodException e)
		{
			return findAddRemoveListnerMethodWithLessCheck(sourceClass, methodName);
		}
		catch (Exception e)
		{
			throw new IntrospectionException(Messages.getString("beans.31", //$NON-NLS-1$
					methodName, listenerType.getName()));
		}
	}
465646
public <E> List<E> find(Class<E> entityClass, Object... primaryKeys)
    {
        List<E> entities = new ArrayList<E>();
        if (primaryKeys == null)
        {
            return entities;
        }
        Set<Object> pKeys = new HashSet<Object>(Arrays.asList(primaryKeys));
        for (Object primaryKey : pKeys)
        {
            E e = find(entityClass, primaryKey);
            if (e != null)
            {
                entities.add(e);
            }
        }
        return entities;
    }
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);
    }
199359
protected Binder findBinderByPropertyName(Class parentObjectType, String propertyName) {
        PropertyNameKey key = new PropertyNameKey(parentObjectType, propertyName);
        Binder binder = (Binder)propertyNameBinders.get(key);
        if (binder == null) {
            // if no direct match was found try to find a match in any super classes
            final Map potentialMatchingBinders = new HashMap();
            for (Iterator i = propertyNameBinders.entrySet().iterator(); i.hasNext();) {
                Map.Entry entry = (Map.Entry)i.next();
                if (((PropertyNameKey)entry.getKey()).getPropertyName().equals(propertyName)) {
                    potentialMatchingBinders.put(((PropertyNameKey)entry.getKey()).getParentObjectType(),
                            entry.getValue());
                }
            }
            binder = (Binder) ClassUtils.getValueFromMapForClass(parentObjectType, potentialMatchingBinders);
            if (binder != null) {
                // remember the lookup so it doesn't have to be discovered again
                registerBinderForPropertyName(parentObjectType, propertyName, binder);
            }
        }
        return binder;
    }