/* (non-Javadoc)
@see com.googlecode.batchfb.Batcher#queryFirst(java.lang.String, java.lang.Class)
542259
@Override
	public <T> Later<T> queryFirst(String fql, Class<T> type)
	{
		return this.getBatchForQuery().queryFirst(fql, type);
	}
675836
public function getFirst()
    {
        if (is_array($this->rows)) {
            $rows = &$this->rows;
        } else {
            $query = clone $this->query;
            $query->setLimit(1);
            $rows = $query->getResult();
        }

        return (isset($rows[0])) ? $rows[0] : null;
    }
792472
private void cmdExecuteQueryActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_buttonExecuteActionPerformed
		try {
			// TODO Handle this such that there is a listener checking the progress of the execution
			Thread queryRunnerThread = new Thread(() -> {
				String queryString = queryTextPane.getText();
                OBDADataQueryAction<?> action = null;
				if (queryString.isEmpty()){
					JOptionPane.showMessageDialog(QueryInterfacePanel.this, "Query editor cannot be empty.");
				} else if (SPARQLQueryUtility.isSelectQuery(queryString)) {
					action = QueryInterfacePanel.this.getExecuteSelectAction();
				} else if (SPARQLQueryUtility.isAskQuery(queryString)){
					action = QueryInterfacePanel.this.getExecuteAskAction();
                } else if ((SPARQLQueryUtility.isConstructQuery(queryString) || SPARQLQueryUtility.isDescribeQuery(queryString)) ){
                    action = QueryInterfacePanel.this.getExecuteGraphQueryAction();
                } else {
                    JOptionPane.showMessageDialog(QueryInterfacePanel.this, "This type of SPARQL expression is not handled. Please use SELECT, ASK, DESCRIBE, or CONSTRUCT.");
                }
				if(action!=null) {
					action.run(queryString);
					execTime = action.getExecutionTime();
					do {
						int rows = action.getNumberOfRows();
						updateStatus(rows);
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							break;
						}
					} while (action.isRunning());
					int rows = action.getNumberOfRows();
						updateStatus(rows);

				}
            });
			queryRunnerThread.start();
		} catch (Exception e) {
			DialogUtils.showQuickErrorDialog(QueryInterfacePanel.this, e);
		}
	}
1110565
@Override
    public Iterator<? extends T> iterator(final long first, final long count) {
        entityManager.getTransaction().begin();

        try {
            final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
            final CriteriaQuery<T> criteria = criteriaBuilder.createQuery(type);
            final Root<T> from = criteria.from(type);

            // setup the sort
            final SortParam<String> param = getSort();

            if(param == null || param.isAscending()) {
                LOG.debug("Setting order by to ascending for {}", type.getName());
                criteria.orderBy(criteriaBuilder.asc(from.get("name")));
            } else {
                LOG.debug("Setting order by to descending for {}", type.getName());
                criteria.orderBy(criteriaBuilder.desc(from.get("name")));
            }

            return entityManager.createQuery(criteria)
                                .setFirstResult((int)first)
                                .setMaxResults((int)count)
                                .getResultList()
                                .iterator();
        } finally {
            entityManager.getTransaction().commit();
        }
    }
643315
public static String getSelectQuery( ASpatialDb db, final TableLevel selectedTable, boolean geomFirst ) throws Exception {
        String tableName = selectedTable.tableName;
        String letter = tableName.substring(0, 1);
        List<String[]> tableColumns = db.getTableColumns(tableName);
        GeometryColumn geometryColumns = db.getGeometryColumnsForTable(tableName);
        String query = "SELECT ";
        if (geomFirst) {
            // first geom
            List<String> nonGeomCols = new ArrayList<String>();
            for( int i = 0; i < tableColumns.size(); i++ ) {
                String colName = tableColumns.get(i)[0];
                if (geometryColumns != null && colName.equals(geometryColumns.geometryColumnName)) {
                    colName = letter + "." + colName + " as " + colName;
                    query += colName;
                } else {
                    nonGeomCols.add(colName);
                }
            }
            // then others
            for( int i = 0; i < nonGeomCols.size(); i++ ) {
                String colName = tableColumns.get(i)[0];
                query += "," + letter + "." + colName;
            }
        } else {
            for( int i = 0; i < tableColumns.size(); i++ ) {
                if (i > 0)
                    query += ",";
                String colName = tableColumns.get(i)[0];
                if (geometryColumns != null && colName.equals(geometryColumns.geometryColumnName)) {
                    colName = letter + "." + colName + " as " + colName;
                    query += colName;
                } else {
                    query += letter + "." + colName;
                }
            }
        }
        query += " FROM " + tableName + " " + letter;
        return query;
    }
443323
@Override
	public QueryRequest<ArrayNode> query(String fql) {
		return this.query(fql, mapper.getTypeFactory().constructType(ArrayNode.class));
	}
201288
public String getFirst(String key)
    {
        if(key == null)
            throw new IllegalArgumentException("Null keys not allowed.");

        List<String> vals = map.get(key);
        if(vals == null || vals.size() == 0)
            return null;

        return vals.get(0);
    }
927743
public Query getQueryImplementation(String jpaQuery, PersistenceDelegator persistenceDelegator, Class mappedClass,
            boolean isNative, final KunderaMetadata kunderaMetadata)
    {
        if (jpaQuery == null)
        {
            throw new QueryHandlerException("Query String should not be null ");
        }

        if (jpaQuery.trim().endsWith(Constants.SEMI_COLON))
        {
            throw new QueryHandlerException("unexpected char: ';' in query [ " + jpaQuery + " ]");
        }

        KunderaQuery kunderaQuery = null;
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        String mappedQuery = appMetadata.getQuery(jpaQuery);

        isNative = mappedQuery != null ? appMetadata.isNative(jpaQuery) : isNative;

        EntityMetadata m = null;

        // In case of named native query
        if (!isNative)
        {
            kunderaQuery = new KunderaQuery(mappedQuery != null ? mappedQuery : jpaQuery, kunderaMetadata);
            KunderaQueryParser parser = new KunderaQueryParser(kunderaQuery);

            parser.parse();

            kunderaQuery.postParsingInit();
            m = kunderaQuery.getEntityMetadata();
        }
        else
        {
            // Means if it is a namedNativeQuery.
            if (appMetadata.isNative(jpaQuery))
            {
                mappedClass = appMetadata.getMappedClass(jpaQuery);
            }

            kunderaQuery = new KunderaQuery(jpaQuery, kunderaMetadata);

            kunderaQuery.isNativeQuery = true;

            m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, mappedClass);

            Field entityClazzField = null;
            try
            {
                entityClazzField = kunderaQuery.getClass().getDeclaredField("entityClass");
                if (entityClazzField != null && !entityClazzField.isAccessible())
                {
                    entityClazzField.setAccessible(true);
                }

                entityClazzField.set(kunderaQuery, mappedClass);
            }
            catch (Exception e)
            {
                log.error(e.getMessage());
                throw new QueryHandlerException(e);
            }
        }

        Query query = null;

        try
        {
            query = getQuery(jpaQuery, persistenceDelegator, m, kunderaQuery, kunderaMetadata);
        }
        catch (Exception e)
        {
            log.error(e.getMessage());
            throw new QueryHandlerException(e);
        }
        return query;
    }
583594
public SimpleEntry getFirst()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(this, tc, "getFirst");

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(this, tc, "getFirst", new Object[] {first, printList()});
    
    return first;          
  }
529458
public BatchFailureListener<QueryBatch> initializeRetryListener(QueryBatchListener queryBatchListener) {
    if(! retryListenersSet.contains(queryBatchListener)) {
      synchronized(this) {
        if(! retryListenersSet.contains(queryBatchListener)) {
          RetryListener retryListener = new RetryListener(queryBatchListener);
          retryListenersSet.add(queryBatchListener);
          return retryListener;
        }
      }
    }
    return null;
  }
628583
public static Record findFirst(String sql, Object... paras) {
		return MAIN.findFirst(sql, paras);
	}
79578
public V getFirst(Object key) {
        List<V> res = getAll(key);
        if (res.isEmpty()) {
            return null;
        } else {
            return res.iterator().next();
        }
    }
1258494
@NonNull
    public Searcher search(@Nullable final String queryString, @Nullable final Object origin) {
        if (queryString != null) {
            query.setQuery(queryString);
            EventBus.getDefault().post(new QueryTextChangeEvent(queryString, origin == null ? this : origin));
        }
        endReached = false;
        lastRequestPage = 0;
        lastResponsePage = -1;
        final int currentRequestId = ++lastRequestId;

        final CompletionHandler searchHandler = new CompletionHandler() {
            @Override
            public void requestCompleted(@Nullable JSONObject content, @Nullable AlgoliaException error) {
                pendingRequests.remove(currentRequestId);
                // NOTE: Canceling any request anterior to the current one.
                //
                // Rationale: Although TCP imposes a server to send responses in the same order as
                // requests, nothing prevents the system from opening multiple connections to the
                // same server, nor the Algolia client to transparently switch to another server
                // between two requests. Therefore the order of responses is not guaranteed.
                for (int i = 0; i < pendingRequests.size(); i++) {
                    int reqId = pendingRequests.keyAt(i);
                    Request request = pendingRequests.valueAt(i);
                    if (reqId < currentRequestId) {
                        cancelRequest(request, reqId);
                    }
                }

                if (currentRequestId <= lastResponseId) {
                    Log.e("Algolia|Searcher", "We already displayed results for request " + lastResponseId
                            + ", current request (" + currentRequestId + ") should have been canceled");
                }

                if (!hasHits(content)) {
                    endReached = true;
                } else {
                    checkIfLastPage(content);
                }

                lastResponseId = currentRequestId;
                lastResponsePage = 0;

                if (error != null) {
                    postError(error, currentRequestId);
                } else {
                    if (content == null) {
                        Log.e("Algolia|Searcher", "content is null but error too.");
                    } else {
                        EventBus.getDefault().post(new ResultEvent(Searcher.this, content, query, currentRequestId));
                        updateListeners(content, false);
                        updateFacetStats(content);
                    }
                }
            }
        };

        final Request searchRequest;
        searchRequest = triggerSearch(searchHandler);
        EventBus.getDefault().post(new SearchEvent(this, query, currentRequestId));
        pendingRequests.put(currentRequestId, searchRequest);
        return this;
    }
296347
public static <T> Query<T> query(Class<T> entityType, Object queryObject) {
        return query(db(), entityType, null, queryObject, null);
    }
872980
@Override
	public <T> T first(final Class<T> type) {
		return findFirst(type).orElseThrow(() -> new DataNotFoundException("query result is empty."));
	}
1299183
@Override
	public Optional<E> first() {
		try (Stream<E> stream = stream()) {
			return stream.findFirst();
		}
	}
582224
def _first(self, query):
        """"""
        result = query.first()
        if result is None:
            raise NotFoundError
        else:
            if result.has_expired(self._expirations):
                raise NotFoundError
            return result