create either a CollectionPrefetcher or a ReferencePrefetcher
773873
public RelationshipPrefetcher createRelationshipPrefetcher(ObjectReferenceDescriptor ord)
    {
        if (ord instanceof CollectionDescriptor)
        {
            CollectionDescriptor cds = (CollectionDescriptor)ord;
            if (cds.isMtoNRelation())
            {
                return new MtoNCollectionPrefetcher(broker, cds);
            }
            else
            {
                return new CollectionPrefetcher(broker, cds);
            }
        }
        else
        {    
            return new ReferencePrefetcher(broker, ord);
        }
    }
4993
public <V> V executeAndFetchFirst(Class<V> returnType) {
        Object o = executeScalar();
        if (null == o) {
            return null;
        }
        return convert(o, returnType);
    }
53213
protected Query buildPrefetchQuery(Collection ids)
    {
        CollectionDescriptor cds = getCollectionDescriptor();
        QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));

        // check if collection must be ordered
        if (!cds.getOrderBy().isEmpty())
        {
            Iterator iter = cds.getOrderBy().iterator();
            while (iter.hasNext())
            {
                query.addOrderBy((FieldHelper) iter.next());
            }
        }

        return query;
    }
918986
private Criteria buildPrefetchCriteriaMultipleKeys(Collection ids, String[] fkCols, String[] itemFkCols,
            FieldDescriptor[] itemPkFields)
    {
        Criteria crit = new Criteria();
        Criteria critValue = new Criteria();
        Iterator iter = ids.iterator();

        for (int i = 0; i < itemPkFields.length; i++)
        {
            crit.addEqualToField(itemPkFields[i].getAttributeName(), itemFkCols[i]);
        }
        
        while (iter.hasNext())
        {
            Criteria c = new Criteria();
            Identity id = (Identity) iter.next();
            Object[] val = id.getPrimaryKeyValues();

            for (int i = 0; i < val.length; i++)
            {

                if (val[i] == null)
                {
                    c.addIsNull(fkCols[i]);
                }
                else
                {
                    c.addEqualTo(fkCols[i], val[i]);
                }

            }
          
            critValue.addOrCriteria(c);
        }

        crit.addAndCriteria(critValue);
        return crit;
    }
596507
private Later<JsonNode> createFetcher() {
		final RequestBuilder call = new GraphRequestBuilder(getGraphEndpoint(), HttpMethod.POST, this.timeout, this.retries);
		
		// This actually creates the correct JSON structure as an array
		String batchValue = JSONUtils.toJSON(this.graphRequests, this.mapper);
		if (log.isLoggable(Level.FINEST))
			log.finest("Batch request is: " + batchValue);

		this.addParams(call, new Param[] { new Param("batch", batchValue) });
		
		final HttpResponse response;
		try {
			response = call.execute();
		} catch (IOException ex) {
			throw new IOFacebookException(ex);
		}
		
		return new Later<JsonNode>() {
			@Override
			public JsonNode get() throws FacebookException
			{
				try {
					if (response.getResponseCode() == HttpURLConnection.HTTP_OK
							|| response.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST
							|| response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
						
						// If it was an error, we will recognize it in the content later.
						// It's possible we should capture all 4XX codes here.
						JsonNode result = mapper.readTree(response.getContentStream());
						
						if (log.isLoggable(Level.FINEST))
							log.finest("Response is: " + result);
						
						return result;
					} else {
						throw new IOFacebookException(
								"Unrecognized error " + response.getResponseCode() + " from "
								+ call + " :: " + StringUtils.read(response.getContentStream()));
					}
				} catch (IOException e) {
					throw new IOFacebookException("Error calling " + call, e);
				}
			}
		};
	}
1240979
def _get_collection(self, collection_uri, request_headers=None):
        """"""

        # get the collection
        status, headers, thecollection = self._rest_get(collection_uri)

        if status != 200:
            msg = self._get_extended_error(thecollection)
            raise exception.IloError(msg)

        while status < 300:
            # verify expected type
            # Don't limit to version 0 here as we will rev to 1.0 at some
            # point hopefully with minimal changes
            ctype = self._get_type(thecollection)
            if (ctype not in ['Collection.0', 'Collection.1']):
                raise exception.IloError("collection not found")

            # if this collection has inline items, return those
            # NOTE:  Collections are very flexible in how the represent
            # members.  They can be inline in the collection as members
            # of the 'Items' array, or they may be href links in the
            # links/Members array.  The could actually be both. Typically,
            # iLO implements the inline (Items) for only when the collection
            # is read only.  We have to render it with the href links when an
            # array contains PATCHable items because its complex to PATCH
            # inline collection members.

            if 'Items' in thecollection:
                # iterate items
                for item in thecollection['Items']:
                    # if the item has a self uri pointer,
                    # supply that for convenience.
                    memberuri = None
                    if 'links' in item and 'self' in item['links']:
                        memberuri = item['links']['self']['href']
                    yield 200, None, item, memberuri

            # else walk the member links
            elif ('links' in thecollection and
                  'Member' in thecollection['links']):
                # iterate members
                for memberuri in thecollection['links']['Member']:
                    # for each member return the resource indicated by the
                    # member link
                    status, headers, member = self._rest_get(memberuri['href'])
                    yield status, headers, member, memberuri['href']

            # page forward if there are more pages in the collection
            if ('links' in thecollection and
                    'NextPage' in thecollection['links']):
                next_link_uri = (collection_uri + '?page=' + str(
                                 thecollection['links']['NextPage']['page']))
                status, headers, thecollection = self._rest_get(next_link_uri)

            # else we are finished iterating the collection
            else:
                break
147794
def _prefetch_items(self,change):
        
        if self.is_initialized:
            view = self.item_view
            
            upper_limit = view.iterable_index+view.iterable_fetch_size-view.iterable_prefetch
            lower_limit = max(0,view.iterable_index+view.iterable_prefetch)
            offset = int(view.iterable_fetch_size/2.0)
            upper_visible_row = view.visible_rect[2]
            lower_visible_row = view.visible_rect[0]
            print("Visible rect = %s"%view.visible_rect)
            
            if upper_visible_row >= upper_limit:
                next_index = max(0,upper_visible_row-offset) # Center on current row
                # Going up works... 
                if next_index>view.iterable_index:
                    print("Auto prefetch upper limit %s!"%upper_limit)
                    view.iterable_index = next_index
                    #view.model().reset()
                    
            # But doewn doesnt?
            elif view.iterable_index>0 and lower_visible_row < lower_limit:
                next_index = max(0,lower_visible_row-offset) # Center on current row
                # Going down works
                if next_index<view.iterable_index:
                    print("Auto prefetch lower limit=%s, iterable=%s, setting next=%s!"%(lower_limit,view.iterable_index,next_index))
                    view.iterable_index = next_index
667196
function StanzaFetcher(db, getInterchangeSession) {
  var self = this;
  self.db = db;
  self._closed = false;
  self.getInterchangeSession = getInterchangeSession;
  self._highWaterMarks = new Chain(self._fetchMostRecentStanzaSeq.bind(self));
  events.EventEmitter.call(this);
}
1198250
public <T, K> JacksonDBCollection<T, K> getReferenceCollection(String collectionName, JavaType type, JavaType keyType) {
        return getReferenceCollection(new JacksonCollectionKey(collectionName, type, keyType));
    }
808581
public <T, K> JacksonDBCollection<T, K> getReferenceCollection(JacksonCollectionKey collectionKey) {
        JacksonDBCollection<T, K> collection = referencedCollectionCache.get(collectionKey);
        if (collection == null) {
            collection = new JacksonDBCollection<T, K>(getDB().getCollection(collectionKey.getName()),
                    collectionKey.getType(), collectionKey.getKeyType(), objectMapper, features);
            referencedCollectionCache.put(collectionKey, collection);
        }
        return collection;
    }
1369807
public static void copyFetches(Fetch<?, ?> from, Fetch<?, ?> to) {
        for (Fetch<?, ?> f : from.getFetches()) {
            Fetch<?, ?> toFetch = to.fetch(f.getAttribute().getName());
            // recursively copy fetches
            copyFetches(f, toFetch);
        }
    }
609527
public void preFetchHBaseMeta() {
    LOG.info("Pre-fetching meta data for all tables");
    final long start = System.currentTimeMillis();
    final ArrayList<Deferred<Object>> deferreds = new ArrayList<Deferred<Object>>();
    deferreds.add(client.prefetchMeta(table));
    deferreds.add(client.prefetchMeta(uidtable));

    // TODO(cl) - meta, tree, etc

    try {
      Deferred.group(deferreds).join();
      LOG.info("Fetched meta data for tables in " +
          (System.currentTimeMillis() - start) + "ms");
    } catch (InterruptedException e) {
      LOG.error("Interrupted", e);
      Thread.currentThread().interrupt();
      return;
    } catch (Exception e) {
      LOG.error("Failed to prefetch meta for our tables", e);
    }
  }
496984
private void loadStorageForFetch(CodeBuilder b, TypeDesc type) {
        b.loadThis();
        b.loadField(SUPPORT_FIELD_NAME, mSupportType);
        TypeDesc storageType = TypeDesc.forClass(Storage.class);

        TypeDesc repositoryType = TypeDesc.forClass(Repository.class);
        b.invokeInterface
            (mSupportType, "getRootRepository", repositoryType, null);
        b.loadConstant(type);

        // This may throw a RepositoryException.
        Label tryStart = b.createLabel().setLocation();
        b.invokeInterface(repositoryType, STORAGE_FOR_METHOD_NAME, storageType,
                          new TypeDesc[]{TypeDesc.forClass(Class.class)});
        Label tryEnd = b.createLabel().setLocation();
        Label noException = b.createLabel();
        b.branch(noException);

        b.exceptionHandler(tryStart, tryEnd,
                           RepositoryException.class.getName());
        b.invokeVirtual
            (RepositoryException.class.getName(), "toFetchException",
             TypeDesc.forClass(FetchException.class), null);
        b.throwObject();

        noException.setLocation();
    }
508440
public final void mFETCH() throws RecognitionException {
		try {
			int _type = FETCH;
			int _channel = DEFAULT_TOKEN_CHANNEL;
			// hql.g:28:7: ( 'fetch' )
			// hql.g:28:9: 'fetch'
			{
			match("fetch"); if (state.failed) return;

			}

			state.type = _type;
			state.channel = _channel;
		}
		finally {
			// do for sure before leaving
		}
	}
161832
def _fetch_all(self):
        
        if self._result_cache is None:
            self._result_cache = list(self.iterator())
            # TODO: Do we have to test for ValuesListIterable, ValuesIterable,
            # and FlatValuesListIterable here?
            if self._iterable_class == ModelIterable:
                for x in self._result_cache:
                    self._set_item_querytime(x)
        if self._prefetch_related_lookups and not self._prefetch_done:
            self._prefetch_related_objects()
1211273
function Collection(response, dispatcher, dispatchOptions) {
  if (!Collection.isCollectionResponse(response)) {
    throw new Error(
        'Cannot create Collection from response that does not have resources');
  }

  this.data = response.data;
  this._response = response;
  this._dispatcher = dispatcher;
  this._dispatchOptions = dispatchOptions;
}
132937
function (context, callback) {
            var self = this,
                model;

            flow()
                .seq("collection", function (cb) {
                    self._findCollection(context, cb, false);
                })
                .seq(function (cb) {
                    var modelFactory = self._getModelFactory();
                    var id = self.$resourceId;
                    id = modelFactory.prototype.convertIdentifier(id);
                    model = this.vars.collection.createItem(id);

                    if (context) {
                        // TODO: build options
                    }
                    self._beforeModelFetch(model, context, cb);
                })
                .seq(function (cb) {
                    model.fetch(null, cb);
                })
                .seq(function () {
                    // fetch hrefs for all sub models and sub collections
                    self._fetchAllHrefsForModel(model, context);
                })
                .exec(function (err) {
                    if (!err) {
                        var processor = self.$restHandler.$restDataSource.getProcessorForModel(model);

                        var body = JSON.stringify(processor.compose(model, "GET", self._getCompositionOptions(context))),
                            response = context.response;

                        response.writeHead(200, {
                            'Content-Type': 'application/json'
                        });

                        response.write(body);
                        response.end();

                        callback(null);
                    } else {
                        if (!(err instanceof HttpError)) {
                            var statusCode = 500;
                            if (err === DataSource.ERROR.NOT_FOUND) {
                                statusCode = 404;
                            }
                            err = new HttpError(err, statusCode);
                        }
                        callback(err);
                    }

                });
        }