Bypass buggy GenericReferenceField querying issue
189455
def generic_in(self, **kwargs):
        ''''''
        query = {}
        for key, value in kwargs.items():
            if not value:
                continue
            # Optimize query for when there is only one value
            if isinstance(value, (list, tuple)) and len(value) == 1:
                value = value[0]
            if isinstance(value, (list, tuple)):
                if all(isinstance(v, basestring) for v in value):
                    ids = [ObjectId(v) for v in value]
                    query['{0}._ref.$id'.format(key)] = {'$in': ids}
                elif all(isinstance(v, DBRef) for v in value):
                    query['{0}._ref'.format(key)] = {'$in': value}
                elif all(isinstance(v, ObjectId) for v in value):
                    query['{0}._ref.$id'.format(key)] = {'$in': value}
            elif isinstance(value, ObjectId):
                query['{0}._ref.$id'.format(key)] = value
            elif isinstance(value, basestring):
                query['{0}._ref.$id'.format(key)] = ObjectId(value)
            else:
                self.error('expect a list of string, ObjectId or DBRef')
        return self(__raw__=query)
230646
@SuppressWarnings("unchecked")
	public <T extends RepresentationModel<T>> T invokeProcessorsFor(T value, ResolvableType referenceType) {

		Assert.notNull(value, "Value must not be null!");
		Assert.notNull(referenceType, "Reference type must not be null!");

		// For Resources implementations, process elements first
		if (RepresentationModelProcessorHandlerMethodReturnValueHandler.COLLECTION_MODEL_TYPE
				.isAssignableFrom(referenceType)) {

			CollectionModel<?> collectionModel = (CollectionModel<?>) value;
			Class<?> rawClass = referenceType.getRawClass();

			if (rawClass == null) {
				throw new IllegalArgumentException(String.format("%s does not expose a raw type!", referenceType));
			}

			ResolvableType elementTargetType = ResolvableType.forClass(CollectionModel.class, rawClass).getGeneric(0);
			List<Object> result = new ArrayList<>(collectionModel.getContent().size());

			for (Object element : collectionModel) {

				ResolvableType elementType = ResolvableType.forClass(element.getClass());

				if (!getRawType(elementTargetType).equals(elementType.getRawClass())) {
					elementTargetType = elementType;
				}

				result.add(invokeProcessorsFor(element, elementTargetType));
			}

			if (RepresentationModelProcessorHandlerMethodReturnValueHandler.CONTENT_FIELD != null) {

				ReflectionUtils.setField( //
						RepresentationModelProcessorHandlerMethodReturnValueHandler.CONTENT_FIELD, //
						collectionModel, //
						result //
				);
			}
		}

		return (T) invokeProcessorsFor((Object) value, referenceType);
	}
87475
def dump(self, fields=None, exclude=None):
        
        exclude = exclude or []
        d = {}
        if fields and self._primary_field not in fields:
            fields = list(fields)
            fields.append(self._primary_field)
        for k, v in self.properties.items():
            if ((not fields) or (k in fields)) and (not exclude or (k not in exclude)):
                if not isinstance(v, ManyToMany):
                    t = v.get_value_for_datastore(self)
                    if t is Lazy:
                        self.refresh()
                        t = v.get_value_for_datastore(self)
                    if isinstance(t, Model):
                        t = t._key
                    d[k] = v.to_str(t)
                else:
                    if fields:
                       d[k] = ','.join([str(x) for x in getattr(self, v._lazy_value(), [])])
        if self._primary_field and d and self._primary_field not in d:
            d[self._primary_field] = str(self._key)
        return d
1249167
@Override
    public T findUniqueUsingQueryModel(QueryModel queryModel)
            throws NoSuchItemException, TooManyItemsException, JeppettoException {
        T result;

        try {
            if (accessControlContextProvider == null
                || accessControlHelper.annotationAllowsAccess(persistentClass, queryModel.getAccessControlContext(), AccessType.Read)) {
                // noinspection unchecked
                result = (T) buildCriteria(queryModel).uniqueResult();
            } else {
                // noinspection unchecked
                result = (T) createAccessControlledQuery(queryModel).uniqueResult();
            }
        } catch (NonUniqueObjectException e) {
            throw new TooManyItemsException(e.getMessage());
        } catch (HibernateException e) {
            throw new JeppettoException(e);
        }

        if (result == null) {
            throw new NoSuchItemException(persistentClass.getSimpleName(), queryModel.toString());
        }

        return result;
    }
560520
private <T> T getReference(final Bean<T> bean) {
        T ret = (T) beanReferences.get(bean);

        if (null != ret) {
            return ret;
        }

        ret = bean.create();

        if (null != ret) {
            beanReferences.put(bean, ret);

            return ret;
        }

        throw new RuntimeException("Can't create reference for bean [" + bean + "]");
    }
402415
def generic_lazy_ref_formatter(view, context, model, name):
    
    return generic_ref_formatter(view, context, model, name, True)
91413
private ManageableCollection getCollectionByQuery(Class collectionClass, Class itemClass, Query query)
            throws ClassNotPersistenceCapableException, PersistenceBrokerException
    {
        if (log.isDebugEnabled()) log.debug("getCollectionByQuery (" + collectionClass + ", " + itemClass + ", " + query + ")");

        ClassDescriptor cld = pb.getClassDescriptor(itemClass);
        ManageableCollection result = null;
        OJBIterator iter = null;
        int fullSize = -1;
        int size = 0;

        final boolean isRetrievalTasksCreated = batchRetrieval && m_retrievalTasks == null;
        if (isRetrievalTasksCreated)
        {
            // Maps ReferenceDescriptors to HashSets of owners
            m_retrievalTasks = new HashMap();
        }

        // ==> enable materialization cache
        pb.getInternalCache().enableMaterializationCache();
        try
        {
            result = (ManageableCollection) collectionClass.newInstance();
            
            // now iterate over all elements and add them to the new collection
            // lifecycle events are disabled
            iter = pb.getIteratorFromQuery(query, cld);
            iter.disableLifeCycleEvents();

            // BRJ : get fullSizefor Query
            // to be removed when Query.fullSize is removed
            if (iter instanceof PagingIterator)
            {
                fullSize = iter.fullSize();
            }

            while (iter.hasNext())
            {
                Object candidate = iter.next();

                /**
                 * MBAIRD
                 * candidate CAN be null in the case of materializing from an iterator based
                 * on a query for a class that is mapped to a table that has other classes
                 * mapped to that table as well, but aren't extents.
                 */
                if (candidate != null)
                {
                    IndirectionHandler handler = ProxyHelper.getIndirectionHandler(candidate);

                    if ((handler != null) || itemClass.isAssignableFrom(candidate.getClass()))
                    {
                        result.ojbAdd(candidate);

                        // BRJ: count added objects
                        // to be removed when Query.fullSize is removed
                        size++;
                    }
                    else
                    {
                        //warn the user
                        log.warn("Candidate object ["+candidate
                                    +"] class ["+candidate.getClass().getName()
                                    +"] is not a subtype of ["+itemClass.getName()
                                    +"] or any type of proxy. NOT INCLUDED in result collection");
                    }
                    if (prefetchProxies && (handler != null)
                            && (cld.getProxyPrefetchingLimit() > 0)
                            && addRetrievalTask(candidate, this))
                    {
                        new PBMaterializationListener(candidate, m_retrievalTasks,
                                this, cld.getProxyPrefetchingLimit());
                    }
                }
            }

            if (isRetrievalTasksCreated)
            {
                // turn off auto prefetching for related proxies
                final Class saveClassToPrefetch = classToPrefetch;
                classToPrefetch = null;
                try
                {
                    performRetrievalTasks();
                }
                finally
                {
                    classToPrefetch = saveClassToPrefetch;
                }
            }

            // BRJ: fire LifeCycleEvents after execution of RetrievalTasks
            // to ensure objects are fully materialized
            Iterator resultIter = result.ojbIterator();
            while (resultIter.hasNext())
            {
                Object obj = resultIter.next();
                afterLookupEvent.setTarget(obj);
                pb.fireBrokerEvent(afterLookupEvent);
                afterLookupEvent.setTarget(null);
            }

            // ==> disable materialization cache
            pb.getInternalCache().disableMaterializationCache();
        }
        catch(RuntimeException e)
        {
            // ==> clear materialization cache
            pb.getInternalCache().doLocalClear();
            throw e;
        }
        catch (Exception ex)
        {
            // ==> clear materialization cache
            pb.getInternalCache().doLocalClear();
            log.error(ex);
            throw new PersistenceBrokerException(ex);
        }
        finally
        {
            if (iter != null)
            {
                iter.releaseDbResources();
            }
            if (isRetrievalTasksCreated)
            {
                m_retrievalTasks = null;
            }
        }

        // BRJ: store fullSize in Query to re-enable deprecated functionality
        // to be removed when Query.fullSize is removed
        if (fullSize < 0)
        {
            fullSize = size;	// use size of result
        }
        query.fullSize(fullSize);
        
        return result;
    }
261404
function resolveReferences() {

    var elementsById = context.elementsById;
    var references = context.references;

    var i, r;

    for (i = 0; (r = references[i]); i++) {
      var element = r.element;
      var reference = elementsById[r.id];
      var property = getModdleDescriptor(element).propertiesByName[r.property];

      if (!reference) {
        context.addWarning({
          message: 'unresolved reference <' + r.id + '>',
          element: r.element,
          property: r.property,
          value: r.id
        });
      }

      if (property.isMany) {
        var collection = element.get(property.name),
            idx = collection.indexOf(r);

        // we replace an existing place holder (idx != -1) or
        // append to the collection instead
        if (idx === -1) {
          idx = collection.length;
        }

        if (!reference) {
          // remove unresolvable reference
          collection.splice(idx, 1);
        } else {
          // add or update reference in collection
          collection[idx] = reference;
        }
      } else {
        element.set(property.name, reference);
      }
    }
  }
83518
private void checkReferenceForeignkeys(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException
    {
        String foreignkey = refDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);

        if ((foreignkey == null) || (foreignkey.length() == 0))
        {
            throw new ConstraintException("The reference "+refDef.getName()+" in class "+refDef.getOwner().getName()+" has no foreignkeys");
        }

        // we know that the class is present because the reference constraints have been checked already
        ClassDescriptorDef ownerClass = (ClassDescriptorDef)refDef.getOwner();
        ArrayList          keyFields;
        FieldDescriptorDef keyField;
        
        try
        {
            keyFields = ownerClass.getFields(foreignkey);
        }
        catch (NoSuchFieldException ex)
        {
            throw new ConstraintException("The reference "+refDef.getName()+" in class "+refDef.getOwner().getName()+" specifies a foreignkey "+ex.getMessage()+" that is not a persistent field in its owner class "+ownerClass.getName());
        }
        for (int idx = 0; idx < keyFields.size(); idx++)
        {
            keyField = (FieldDescriptorDef)keyFields.get(idx);
            if (keyField.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
            {
                throw new ConstraintException("The reference "+refDef.getName()+" in class "+ownerClass.getName()+" uses the field "+keyField.getName()+" as foreignkey although this field is ignored in this class");
            }
        }
            
        // for the referenced class and any subtype that is instantiable (i.e. not an interface or abstract class)
        // there must be the same number of primary keys and the jdbc types of the primary keys must
        // match the jdbc types of the foreignkeys (in the correct order)
        String             targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF);
        ArrayList          queue           = new ArrayList();
        ClassDescriptorDef referencedClass;
        ArrayList          primFields;
        FieldDescriptorDef primField;
        String             primType;
        String             keyType;
        
        queue.add(modelDef.getClass(targetClassName));

        while (!queue.isEmpty())
        {
            referencedClass = (ClassDescriptorDef)queue.get(0);
            queue.remove(0);

            for (Iterator it = referencedClass.getExtentClasses(); it.hasNext();)
            {
                queue.add(it.next());
            }
            if (!referencedClass.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true))
            {
                continue;
            }
            primFields = referencedClass.getPrimaryKeys();
            if (primFields.size() != keyFields.size())
            {
                throw new ConstraintException("The number of foreignkeys ("+keyFields.size()+") of the reference "+refDef.getName()+" in class "+refDef.getOwner().getName()+" doesn't match the number of primarykeys ("+primFields.size()+") of the referenced class (or its subclass) "+referencedClass.getName());
            }
            for (int idx = 0; idx < primFields.size(); idx++)
            {
                keyField  = (FieldDescriptorDef)keyFields.get(idx);
                primField = (FieldDescriptorDef)primFields.get(idx);
                primType  = primField.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);
                keyType   = keyField.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE);
                if (!primType.equals(keyType))
                {
                    throw new ConstraintException("The jdbc-type of foreignkey "+keyField.getName()+" of the reference "+refDef.getName()+" in class "+refDef.getOwner().getName()+" doesn't match the jdbc-type of the corresponding primarykey "+primField.getName()+" of the referenced class (or its subclass) "+referencedClass.getName());
                }
            }
        }
    }
147846
@Override
    void findReferencedClassNames(final Set<String> classNameListOut) {
        if (classBound != null) {
            classBound.findReferencedClassNames(classNameListOut);
        }
        for (final ReferenceTypeSignature typeSignature : interfaceBounds) {
            typeSignature.findReferencedClassNames(classNameListOut);
        }
    }
298903
private QueryBuilder genericRequest(String type, String value) throws Exception {
        JSONObject op = new JSONObject();
        op.put(type, value);
        JSONArray operations = (JSONArray) request.get(Constants.REQUEST_OPERATIONS);
        operations.put(op);
        request.remove(Constants.REQUEST_OPERATIONS);
        request.put(Constants.REQUEST_OPERATIONS, operations);
        return this;
    }
205210
def get_ref(cls, state, obj_alloc_id, field_class_name, field_name, field_type):
        
        # resolve field
        field_class = state.javavm_classloader.get_class(field_class_name)
        field_id = resolve_field(state, field_class, field_name, field_type)
        # return field ref
        return cls.from_field_id(obj_alloc_id, field_id)
662651
def get_db_distinct(queryset, field, func, **params):
    
    while True:
        try:
            value = func(**params)
            queryset.get(**{field: value})
        except ObjectDoesNotExist:
            break
    return value
646069
protected void checkReferenceable(ImportNodeData currentNodeInfo, String olUuid) throws RepositoryException
   {
      // if node is in version storage - do not assign new id from jcr:uuid
      // property
      if (Constants.JCR_VERSION_STORAGE_PATH.getDepth() + 3 <= currentNodeInfo.getQPath().getDepth()
         && currentNodeInfo.getQPath().getEntries()[Constants.JCR_VERSION_STORAGE_PATH.getDepth() + 3]
            .equals(Constants.JCR_FROZENNODE)
         && currentNodeInfo.getQPath().isDescendantOf(Constants.JCR_VERSION_STORAGE_PATH))
      {
         return;
      }

      String identifier = validateUuidCollision(olUuid);

      if (identifier != null)
      {
         reloadChangesInfoAfterUC(currentNodeInfo, identifier);
      }
      else
      {
         currentNodeInfo.setIsNewIdentifer(true);
      }
      if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING)
      {
         NodeData parentNode = getParent();
         currentNodeInfo.setParentIdentifer(parentNode.getIdentifier());
         if (parentNode instanceof ImportNodeData && ((ImportNodeData)parentNode).isTemporary())
         {
            // remove the temporary parent
            tree.pop();
         }
      }
   }
282991
void checkFieldRef(ClassFile cf,
                       ConstantPool.CONSTANT_Fieldref_info fri) throws ConstantPoolException {
        String clname = nameFromRefType(fri.getClassName());
        CONSTANT_NameAndType_info nti = fri.getNameAndTypeInfo();
        String name = nti.getName();
        String type = nti.getType();

        if (clname != null) {
            clname = resolveMember(cf, clname, name, type, false, true);
            DeprData dd = db.getFieldDeprecated(clname, name);
            if (dd != null) {
                printField("scan.out.usesfield", cf, clname, name, dd.isForRemoval());
            }
        }
    }
513488
@Override
    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "getObjectInstance", new Object[] { obj, name, nameCtx, environment });
        Object ret = null;

        if (obj instanceof Reference) {
            Reference ref = (Reference) obj;
            String clsName = ref.getClassName();

            if (clsName.equals(ConnectionFactory.class.getName())) {
                ret = this.createConnectionFactory();
                ((JmsConnectionFactory) ret).setReference(ref);
            }

            else if (clsName.equals(QueueConnectionFactory.class.getName())) {
                ret = this.createQueueConnectionFactory();
                ((JmsQueueConnectionFactory) ret).setReference(ref);
            }

            else if (clsName.equals(TopicConnectionFactory.class.getName())) {
                ret = this.createTopicConnectionFactory();
                ((JmsTopicConnectionFactory) ret).setReference(ref);
            }

            else if (clsName.equals(JmsQueueImpl.class.getName())) {
                ret = new JmsQueueImpl(ref);
            }

            else if (clsName.equals(JmsTopicImpl.class.getName())) {
                ret = new JmsTopicImpl(ref);
            }

            else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    SibTr.debug(tc, "class name is " + clsName);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "getObjectInstance", ret);
        return ret;
    }
1238339
@SuppressWarnings({"static-method", "checkstyle:npathcomplexity"})
	public void loadBuilderPreferences(GeneratorConfig2 generatorConfig, IProject context) {
		final IPreferenceStore preferenceStore = SARLPreferences.getSARLPreferencesFor(context);
		if (preferenceStore != null) {
			if (preferenceStore.contains(PREF_GENERATED_TEST_SOURCE_FOLDER)) {
				generatorConfig.setGeneratedTestSourceFolder(preferenceStore.getString(PREF_GENERATED_TEST_SOURCE_FOLDER));
			}
			if (preferenceStore.contains(PREF_GENERATE_INLINE)) {
				generatorConfig.setGenerateInlineAnnotation(preferenceStore.getBoolean(PREF_GENERATE_INLINE));
			}
			if (generatorConfig.isGenerateInlineAnnotation()
					&& preferenceStore.contains(PREF_USE_EXPRESSION_INTERPRETER)) {
				generatorConfig.setUseExpressionInterpreterForInlineAnnotation(preferenceStore.getBoolean(
						PREF_USE_EXPRESSION_INTERPRETER));
			}
			if (preferenceStore.contains(PREF_GENERATE_PURE)) {
				generatorConfig.setGeneratePureAnnotation(preferenceStore.getBoolean(PREF_GENERATE_PURE));
			}
			if (preferenceStore.contains(PREF_GENERATE_EQUALITY_TEST_FUNCTIONS)) {
				generatorConfig.setGenerateEqualityTestFunctions(preferenceStore.getBoolean(PREF_GENERATE_EQUALITY_TEST_FUNCTIONS));
			}
			if (preferenceStore.contains(PREF_GENERATE_TOSTRING_FUNCTIONS)) {
				generatorConfig.setGenerateToStringFunctions(preferenceStore.getBoolean(PREF_GENERATE_TOSTRING_FUNCTIONS));
			}
			if (preferenceStore.contains(PREF_GENERATE_CLONE_FUNCTIONS)) {
				generatorConfig.setGenerateCloneFunctions(preferenceStore.getBoolean(PREF_GENERATE_CLONE_FUNCTIONS));
			}
			if (preferenceStore.contains(PREF_GENERATE_SERIAL_NUMBER_FIELDS)) {
				generatorConfig.setGenerateSerialNumberFields(preferenceStore.getBoolean(PREF_GENERATE_SERIAL_NUMBER_FIELDS));
			}
		}
	}